#!/usr/bin/perl
package TEdit::Exec;

# I made this before I knew of IPC::System::Simple.  Oops.

use strict;
use warnings qw( all );
use IPC::Open2;

sub new {
	my $class = shift;
	my $args = shift;
        my $self = {};
	bless($self,$class);
	
	$self->{_error} = undef;
	$self->{_ran} = 0;
	return($self->error("please specify args"))
		unless ref($args->{cmdargs});
	$self->{cmd} = shift(@{$args->{cmdargs}});
	$self->{args} = $args->{cmdargs};
	$self->{input} = $args->{input} || undef;

	$self->init();
	return $self;
};

sub init {
	my $self = shift;
	$self->exec();
}

sub exec {
	my $self = shift;
	my $c_in_fh;
	my $c_out_fh;
	
	my $c_pid = open2($c_out_fh,$c_in_fh,$self->{cmd},@{$self->{args}})
		or return($self->error("can't open pipe: $!"));
	$self->{_ran} = 1;
	if(defined($self->{input})) {
		print $c_in_fh $self->{input};
	}
	close($c_in_fh);
	my @lines = <$c_out_fh>;
	close($c_out_fh);
	waitpid($c_pid,0);
	$self->{_output} = join("\n",@lines);
	$self->{_unix_returncode} = $? >> 8;
	$self->{_perl_returncode} = $?;
}

sub output { 		return($_[0]->{_output}); 		}
sub returncode {	return($_[0]->{_unix_returncode});	}

sub error {
        my $self = shift;
        if (@_) {
                $self->{_error} = shift;
        }
        return unless defined($self->{_error}) && $self->{_error};
        return($self->{_error});
}

1;

__END__
